import { _decorator, CCFloat, Component, EventTouch, Input, input, math, Node, v3, Vec3 } from 'cc';
import { VirtualInput } from '../input/VirtualInput';
const { ccclass, property } = _decorator;

@ccclass('UIJoystick')
export class UIJoystick extends Component {

    @property(Node)
    private StickBg: Node = null!;

    @property(Node)
    private Thumbnail: Node = null!;

    @property({ type: CCFloat})
    radius: number = 0;

    initPositon: Vec3 = v3()

    start() {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        input.on(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);

        this.initPositon = this.StickBg.worldPosition.clone();
    }

    onDestroy() {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        input.off(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    update(deltaTime: number) {
        
    }


    onTouchStart(touchEvent: EventTouch)
    {
        // 移动stick bg到按下的位置
        const x = touchEvent.touch.getUILocationX();
        const y = touchEvent.touch.getUILocationY();

        this.StickBg.setWorldPosition(x, y, 0);
    }

    onTouchMove(touchEvent: EventTouch)
    {
        // 获取摇杆在 UI 的位置
        let x = touchEvent.touch.getUILocationX();
        let y = touchEvent.touch.getUILocationY();

        let worldPosition = new Vec3(x, y, 0);
        let localPosition = v3();

        // 转化摇杆的位置到背景图的本地坐标
        this.StickBg.inverseTransformPoint(localPosition, worldPosition);
        let thumbnailPosition = v3();
        let len = localPosition.length();
        localPosition.normalize();
        Vec3.scaleAndAdd(thumbnailPosition, v3(), localPosition, math.clamp(len, 0, this.radius));

        this.Thumbnail.setPosition(thumbnailPosition);

        // 将计算的结果赋予给 Input
        VirtualInput.horizontal = this.Thumbnail.position.x / this.radius;
        VirtualInput.vertical = this.Thumbnail.position.y / this.radius;

    }

    onTouchEnd()
    {
        this.StickBg.setWorldPosition(this.initPositon);
        this.Thumbnail.setPosition(Vec3.ZERO);

        VirtualInput.vertical = 0;
        VirtualInput.horizontal = 0;
    }
}

